package stone926.mods.more_enchantments.enchantments;

import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentTarget;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.effect.StatusEffect;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.item.AxeItem;
import net.minecraft.item.ItemStack;
import net.minecraft.item.TridentItem;

public class EffectEnchantment extends Enchantment {

  private final int maxEnchLevel;
  private final StatusEffect effect;
  private final int durationSeconds;

  public EffectEnchantment(int maxEnchLevel, StatusEffect effect, int durationSeconds) {
    super(Rarity.UNCOMMON, EnchantmentTarget.WEAPON, new EquipmentSlot[]{EquipmentSlot.MAINHAND});
    this.maxEnchLevel = maxEnchLevel;
    this.effect = effect;
    this.durationSeconds = durationSeconds;
  }

  @Override
  public boolean isAvailableForRandomSelection() {
    return false;
  }

  @Override
  public boolean isAvailableForEnchantedBookOffer() {
    return false;
  }

  @Override
  public boolean isTreasure() {
    return true;
  }

  @Override
  public int getMaxLevel() {
    return maxEnchLevel;
  }

  @Override
  public boolean isAcceptableItem(ItemStack stack) {
    return super.isAcceptableItem(stack) || stack.getItem() instanceof AxeItem || stack.getItem() instanceof TridentItem;
  }

  public StatusEffect getEffect(int lvl, LivingEntity user, LivingEntity target) {
    return effect;
  }

  public int getDurationSeconds(int lvl, LivingEntity user, LivingEntity target) {
    return durationSeconds * lvl;
  }

  public StatusEffectInstance getEffectInstance(int lvl, LivingEntity user, LivingEntity target) {
    return new StatusEffectInstance(
      getEffect(lvl, user, target),
      getDurationSeconds(lvl, user, target) * 20,
      Math.min(255, lvl - 1)
    );
  }

  @Override
  public void onTargetDamaged(LivingEntity user, Entity target, int level) {
    super.onTargetDamaged(user, target, level);
    if (target instanceof LivingEntity livingEntity && level > 0) {
      livingEntity.addStatusEffect(getEffectInstance(level, user, livingEntity), user);
    }
  }

}
